package com.jinbei.mq;

import com.alibaba.fastjson.JSONObject;
import com.jinbei.cache.EhCacheService;
import com.jinbei.common.Contants.Contants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Component;

import javax.jms.TextMessage;

/**
 * @author zflu
 * activemq 消费者
 * Created by lucky on 2018/8/7.
 */
@Component
public class ActiveMqConsumer {

    Logger logger = LoggerFactory.getLogger(ActiveMqConsumer.class);

    @Autowired
    private EhCacheService ehCacheService;

    @JmsListener(destination = "${activemq.topic}" , containerFactory = "topicListenerFactory")
    public void subscribe(TextMessage text){
        try {
            logger.info("subscribe : "+ text.getText());
            if(text != null){
                JSONObject json = JSONObject.parseObject(text.getText());
                String key = json.getString(Contants.TYPE);
                String data = json.getString(Contants.DATA);
                String command = json.getString(Contants.COMMAND);
                switch (command){
                    case Contants.ADD:
                        //将消息数据存入ehcache
                        ehCacheService.addCache(key,data);
                        break;
                    case Contants.UPDATE:
                        ehCacheService.addCache(key,data);
                        break;
                    case Contants.DELETE:
                        ehCacheService.removeCache(key);
                        break;
                    default:
                        logger.info("method is not found ..... command:"+command);
                }
            }
        } catch (Exception e) {
            logger.error("JSM订阅解析异常!  :",e.getMessage());
        }
    }
}
